package com.dongqi.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongqi.myblog.exception.NotFoundException;
import com.dongqi.myblog.po.TBlog;
import com.dongqi.myblog.mapper.TBlogMapper;
import com.dongqi.myblog.po.TBlogTag;
import com.dongqi.myblog.po.TComment;
import com.dongqi.myblog.po.TUser;
import com.dongqi.myblog.po.vo.BlogQuery;
import com.dongqi.myblog.service.OssService;
import com.dongqi.myblog.service.TBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dongqi.myblog.service.TBlogTagService;
import com.dongqi.myblog.service.TCommentService;
import com.dongqi.myblog.util.MarkdownUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dongqi
 * @since 2020-08-03
 */
@Service
public class TBlogServiceImpl extends ServiceImpl<TBlogMapper, TBlog> implements TBlogService {

    @Autowired
    private TBlogTagServiceImpl blogTagService;
    @Autowired
    private TCommentService commentService;
    @Autowired
    private OssService ossService;

    /**
     * 分页查询博客（条件）
     */
    @Override
    public Page<BlogQuery> listBlogs(TBlog blog, Page<BlogQuery> page) {
        QueryWrapper<BlogQuery> wrapper = new QueryWrapper<>();
        String title = blog.getTitle();
        Long typeId = blog.getTypeId();
        Boolean recommend = blog.getRecommend();
        if (!StringUtils.isEmpty(title)){
            wrapper.like("title",title);
        }
        if (!StringUtils.isEmpty(typeId)&&typeId!=-1){
            wrapper.eq("type_id",typeId);
        }
        if (recommend!=null&&recommend==true){
            wrapper.eq("recommend",recommend);
        }
        wrapper.eq("published",true);
        //wrapper.orderByDesc("create_time");
        List<BlogQuery> tBlogs = this.baseMapper.listBlogs(page, wrapper);
        return page.setRecords(tBlogs);
    }

    /**
     * 根据id获取博客
     */
    @Override
    public TBlog getBlogById(Long id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 更新博客
     */
    @Override
    public TBlog updateBlogById(TBlog blog) {
        TBlog tBlog = this.baseMapper.selectById(blog.getId());
        if (tBlog==null){
            throw new NotFoundException("博客不存在");
        }
        this.baseMapper.updateById(blog);
        return blog;
    }

    /**
     * 新增博客
     */
    @Override
    @Transactional
    public int insertBlog(BlogQuery blog, TUser user,MultipartFile file) {
        if (!file.isEmpty()){
            String url = ossService.uploadFileAvatar(file);
            blog.setFirstPicture(url);
        }
        Long id = blog.getId();
        int insert = -1;
        //blog id为空，新增blog
        if (id==null){
            blog.setUserId(user.getId());
            insert = this.baseMapper.insert(blog);
            if (blog.getTagIds()!=null){
                for(Long t : blog.getTagIds()){
                    TBlogTag tBlogTag = new TBlogTag();
                    tBlogTag.setBlogId(blog.getId());
                    tBlogTag.setTagId(t);
                    blogTagService.save(tBlogTag);
                }
            }
        } else {
            //如果blog 的id不为空，那么就根据id更新blog
            insert = this.baseMapper.updateById(blog);
        }
        return insert;
    }

    /**
     * 删除博客（先删除从表再删除主表）
     */
    @Override
    @Transactional
    public boolean deleteBlog(Long id) {
        QueryWrapper<TComment> wrapperComm = new QueryWrapper<>();
        wrapperComm.eq("blog_id",id);
        commentService.remove(wrapperComm);
        QueryWrapper<TBlogTag> wrapperTag = new QueryWrapper<>();
        wrapperTag.eq("blog_id",id);
        blogTagService.remove(wrapperTag);
        return this.baseMapper.deleteById(id)>0?true:false;
    }

    /**
     * 首页的分页查询
     */
    @Override
    public Page<BlogQuery> listIndex(TBlog blog, Page<BlogQuery> page) {
        QueryWrapper<BlogQuery> wrapper = new QueryWrapper<>();
        wrapper.eq("published",true);
        return page.setRecords(this.baseMapper.listIndex(page,wrapper));
    }

    /**
     * 分类页的分页查询
     */
    @Override
    public Page<BlogQuery> listType(Long id, Page<BlogQuery> page) {
        QueryWrapper<BlogQuery> wrapper = new QueryWrapper<>();
        wrapper.eq("published",true)
                .eq("type_id",id);
        return page.setRecords(this.baseMapper.listIndex(page,wrapper));
    }


    /**
     * 全局搜索
     */
    @Override
    public Page<BlogQuery> listSearch(String query, Page<BlogQuery> page) {
        //index分页blog
        QueryWrapper<BlogQuery> wrapper = new QueryWrapper();
        wrapper.like("title",query)
                .or()
                .like("content",query);
        page.setRecords(this.baseMapper.listIndex(page,wrapper));
        return page;
    }

    /**
     * 前台功能，根据id查询blog
     */
    @Override
    public TBlog selectBlog(Long id) {
        return this.baseMapper.selectBlog(id);
    }

    /**
     * 获取blog并将内容转换成markdown
     */
    @Override
    public TBlog getAndConvert(Long id) {
        TBlog blog = selectBlog(id);
        if (blog==null){
            throw new NotFoundException("该blog不存在");
        }
        String content = blog.getContent();
        blog.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        this.updateViews(blog);
        return blog;
    }

    /**
     * 更新访问量
     */
    @Override
    @Transactional
    public Boolean updateViews(TBlog blog) {
        TBlog update = new TBlog();
        update.setCommentabled(null);
        update.setAppreciation(null);
        update.setShareStatement(null);
        update.setRecommend(null);
        update.setId(blog.getId());
        update.setViews(blog.getViews()+1);
        return this.updateById(update);
    }

    /**
     * 根据某一个标签Id查找对应的所有blog
     */
    @Override
    public Page<TBlog> blogsByTag(Page<TBlog> page, Long tagId) {
        return page.setRecords(this.baseMapper.blogsByTag(page,tagId));
    }

    /**
     * 根据年份归档的方法
     */
    @Override
    public Map<String, List<TBlog>> archiveBlog() {
        List<String> years = this.baseMapper.findGroupYear();
        Map<String,List<TBlog>> map = new LinkedHashMap<>();
        for(String year:years){
            List<TBlog> blogs = this.baseMapper.findBlogByYear(year);
            map.put(year,blogs);
        }
        return map;
    }

    /**
     * 查询一共有多少条Blog数据
     */
    @Override
    public Long countBlog() {
        Long count = this.baseMapper.countBlog();
        return count;
    }

}
